define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'classroom/question/index' + location.search,
                    add_url: 'classroom/question/add',
                    edit_url: 'classroom/question/edit',
                    del_url: 'classroom/question/del',
                    multi_url: 'classroom/question/multi',
                    import_url: 'classroom/question/import',
                    table: 'classroom_question',
                }
            });

            var table = $("#table");
            
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone,.btn-edit,.btn-add").data("area", ["95%","95%"]);
                $(".btn-editone,.btn-edit,.btn-add").data("shade", 0.5);
            });

            // 查看试卷
            $(document).on("click",".show_test",function () {
                let ids = $(this).attr('data-id');
                Fast.api.open('classroom/test/show?ids='+ids,'查看');
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'test_id', title: __('Test_id'),
                            formatter: function (value, row, index) {
                                if(value){
                                    return `<bottom class="btn btn-xs btn-info show_test" data-id="${value}"><i class="fa fa-file-text-o"></i>&nbsp;&nbsp;ID：${value}</bottom>`;
                                } else {
                                    return '<span class="btn btn-xs btn-primary disabled">无</span>';
                                }
                            }
                        },
                        {field: 'title', title: __('Title'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'type', title: __('Type'), searchList: {"1":__('Type 1'),"2":__('Type 2'),"3":__('Type 3'),"4":__('Type 4'),"5":__('Type 5')}, formatter: Table.api.formatter.normal},
                        {field: 'answer', title: __('Answer'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'score', title: __('Score')},
                        {field: 'weigh', title: __('Weigh'), operate: false},
                        // {field: 'test.title', title: __('Test.title'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                // 设置单选答案只有一个
                $(document).on("click",".answer_radio",function () {
                    // 重置所有值
                    $(this).parent().parent().parent().find("input").prop('checked', false);
                    $(this).parent().parent().find("label").attr('data-value','0');

                    let v = $(this).parent().attr('data-value');
                    console.log('值',v);
                    if(parseInt(v) === 1){
                        $(this).prop('checked', false);
                        $(this).parent().attr('data-value','0');
                    } else {
                        $(this).prop('checked', true);
                        $(this).parent().attr('data-value','1');
                    }
                });
                // 题目类型选择 $("#c-type").change
                $("input[type=radio][name='row[type]']").change(function () {
                    let type = parseInt($(this).val());
                    console.log(type);
                    $("#c-title").attr('placeholder',"");
                    switch (type) {
                        case 1:
                            $(".radio_box").show();
                            $(".multiple_box").hide();
                            $(".true_box").hide();
                            $(".completion_box").hide();
                            $(".ask_box").hide();
                            break;
                        case 2:
                            $(".radio_box").hide();
                            $(".multiple_box").show();
                            $(".true_box").hide();
                            $(".completion_box").hide();
                            $(".ask_box").hide();

                            break;
                        case 3:
                            $(".radio_box").hide();
                            $(".multiple_box").hide();
                            $(".true_box").show();
                            $(".completion_box").hide();
                            $(".ask_box").hide();

                            break;
                        case 4:
                            $(".radio_box").hide();
                            $(".multiple_box").hide();
                            $(".true_box").hide();
                            $(".completion_box").show();
                            $("#c-title").attr('placeholder',"填空题案例：口算题：2 + 5 = (________)；7 + 12 = (________)。");
                            $(".ask_box").hide();

                            break;
                        case 5:
                            $(".radio_box").hide();
                            $(".multiple_box").hide();
                            $(".true_box").hide();
                            $(".completion_box").hide();
                            $(".ask_box").show();

                            break;
                    }
                });
                /***** 填空题 start *****/
                // console.log('新增填空项');
                $(".btn-completion").click(function () {
                    // 获取鼠标下标位置
                    const cursorIndex = $('textarea').prop('selectionStart');
                    // console.log('Cursor index:', cursorIndex);
                    let insertText = ` (________) `;
                    let value = $("#c-title").val();

                    // 判断是否在插入字符串内
                    let newValue = value.slice(0, cursorIndex) + insertText + value.slice(cursorIndex);
                    $("#c-title").val(newValue);

                    Controller.api.th_text();
                });
                // console.log('新增匹配答案');
                // console.log('监控文本框修改');
                $("#c-title").keyup(function () {
                    let inputStr = $("#c-title").val();
                    // 正则表达式，匹配 " (________) "
                    const regex = /\(________\)/g;
                    // 使用 match 方法找到所有匹配项
                    const matches = inputStr.match(regex);
                    // 计算匹配项的数量
                    const count = matches ? matches.length : 0;
                    // 判断占位文字数量和设置答案是否相同
                    let option_item_num = $(".completion_options .option_item").length;
                    // console.log(`关键字 " (________) " 出现的次数:`,count,'option_item_num出现次数:',option_item_num);

                    if(option_item_num < count){
                        let diff_num = count - option_item_num;
                        for(let i = 1;i <= diff_num; i++){
                            Controller.api.th_text();
                        }
                    } else if(option_item_num > count) {
                        let diff_num = option_item_num - count;
                        for(let i = 1;i <= diff_num; i++){
                            $(".completion_options .option_item:last").remove();
                        }
                    }

                });
                // console.log('监控文本框修改');
                $(document).on("click",".completion_value_append",function () {
                    let current = $(this).parent().find('.option_item_num').text();
                    current = current.replace('（','');
                    current = current.replace('）','');
                    let html = `<div class="completion_value_item">
                                <input type="text" name="row[completion_json][${current}][]" class="form-control" autocomplete="off">
                                <div class="btn btn-sm btn-danger completion_remove"><i class="fa fa-times"></i></div>
                            </div>`;
                    $(this).parent().find(".completion_values").append(html);
                });
                // console.log('删除匹配答案');
                $(document).on("click",".completion_remove",function () {
                    let value_item_num = $(this).parent().parent().find(".completion_remove").length;
                    console.log('value_item_num',value_item_num);
                    if(value_item_num === 1){
                        //---------------- 获取 occurrence start ----------------//
                        // 获取点击的 .completion_remove 所属的 .option_item
                        let optionItem = $(this).closest('.option_item');
                        // 获取 .option_item 在 .completion_options 中的索引
                        let occurrence = $('.option_item').index(optionItem) + 1;
                        //---------------- 获取 occurrence end ----------------//
                        Controller.api.remove_keywords(occurrence,$(this).parent().parent());
                    } else {
                        $(this).parent().remove();
                    }
                });
                // console.log('移除整个匹配答案');
                $(document).on("click",".completion_value_remove",function () {
                    let occurrence = $(this).index(".completion_value_remove") + 1;
                    Controller.api.remove_keywords(occurrence,$(this));
                });
                /***** 初始化题目分值 end *****/


                /***** 初始化题目分值 start *****/
                let score_config = Config.score_config;
                if(score_config){
                    let type_v = $("input[name='row[type]']:checked").val();
                    let c_score = score_config[type_v] || 0;
                    $("#c-score").val(c_score);
                }
                $("input[type=radio][name='row[type]']").change(function () {
                    if(score_config){
                        let c_score = score_config[this.value] || 0;
                        $("#c-score").val(c_score);
                    }
                });
                /***** 初始化题目分值 end *****/


                Form.api.bindevent($("form[role=form]"));
            },
            th_text: function () {
                // 添加匹配答案
                let completion_options_num = parseInt($(".completion_options .option_item").length) + 1;
                let html = `<div class="option_item">
                                        <div class="completion_title">填空 <b class="option_item_num">（${completion_options_num}）</b> 答案</div>
                                        <div class="completion_values">
                                            <div class="completion_value_item">
                                                <input type="text" name="row[completion_json][${completion_options_num}][]" class="form-control" autocomplete="off">
                                                <div class="btn btn-sm btn-danger completion_remove"><i class="fa fa-times"></i></div>
                                            </div>
                                        </div>
                                        <button type="button" class="btn btn-sm btn-success completion_value_append"><i class="fa fa-plus"></i> 追加类似答案</button>
                                        <button type="button" class="btn btn-sm btn-warning completion_value_remove"><i class="fa fa-times"></i> 移除填空答案</button>
                                    </div>`;
                $(".completion_options").append(html);
            },
            remove_keywords: function (occurrence,divElement) {
                //---------------- 移除当前点击的占位符 start ----------------//
                let inputStr = $("#c-title").val();
                // 要替换的单词
                let wordToReplace = "(________)";
                // 替换后的单词
                let newWord = "";
                // 使用正则表达式查找所有匹配项
                let regex = new RegExp(`\\(________\\)`, 'g');
                let match;
                let count = 0;
                let startIndex = 0;
                // 查找第 occurrence 次出现的位置
                while ((match = regex.exec(inputStr)) !== null) {
                    count++;
                    if (count === occurrence) {
                        startIndex = match.index;
                        break;
                    }
                }
                // 如果找到了第 occurrence 次出现的位置，进行替换
                if (startIndex !== 0) {
                    inputStr = inputStr.substring(0, startIndex) + newWord + inputStr.substring(startIndex + wordToReplace.length);
                }
                $("#c-title").val(inputStr);
                //---------------- 移除当前点击的占位符 end ----------------//

                divElement.parent().remove();
                // 获取所有答案项数量
                $(".option_item_num").each(function (k,v) {
                    let num = k+1;
                    $(this).html(`（${num}）`);
                    // 重设name
                    $(this).parent().parent().find(".completion_values .completion_value_item input").each(function (k2,v2) {
                        $(this).attr('name',"row[completion_json]["+num+"][]");
                    });
                });
            },
        }
    };
    return Controller;
});